package cn.dengyonsheng.mail_send_service.services;

import cn.dengyonsheng.mail_send_service.config.MailConfig;
import cn.dengyonsheng.mail_send_service.config.RabbitConfig;
import cn.dengyonsheng.mail_send_service.entities.MailMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = RabbitConfig.QUEUE_MailSend)
public class MailConsumer {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final MailSender mailSender;
    private final MailConfig mailConfig;

    @Autowired
    public MailConsumer(MailSender mailSender, MailConfig mailConfig) {
        this.mailSender = mailSender;
        this.mailConfig = mailConfig;
    }

    @RabbitHandler
    public void process(String mailMessageJson) throws InterruptedException, JsonProcessingException {
        // 消息对象反序列化
        MailMessage mailMessage = MailMessage.parseJson(mailMessageJson);
        // 自定义对象转系统对象
        SimpleMailMessage simpleMailMessage = mailMessage.toSimpleMailMessage();
        // 使用注入的配置信息
        simpleMailMessage.setFrom(mailConfig.getUsername());
        mailSender.send(simpleMailMessage);
        logger.info("成功发送邮件： \n" + mailMessage);
        // 模拟限制邮件发送的频率
        Thread.sleep(5000);
    }
}
